/**
 * @file out_flash.c
 * @author Linquan  
 * @brief  
 *          when erase ,erase one block,
 *          one page = 2K,one block = 2K * 64
 *          the nand flash has 1024 blocks
 *          the flash start address is 0 (OUT_FLASH_ADDR_START)
 * 
 * @version 0.2
 * @date 2024-02-26
 * 
 * @copyright Copyright (c) 2024
 * 
 */
#include "out_flash.h"
#include "stdio.h"
#include "string.h"


#define OUT_FLASH_ADDR_START        0
#define OUT_PAGE_SIZE             (1024*2)       // 页大小
#define OUT_PAGES_PER_BLIOCK      64        // 一块的页数
#define OUT_BLOCK_NUM             1024       // 块数
#define OUT_FLASH_SIZE            (OUT_BLOCK_NUM*OUT_PAGES_PER_BLIOCK*OUT_PAGE_SIZE)

uint8_t out_flash_array[OUT_FLASH_SIZE]= {0};



void out_flash_init()
{
    memset(out_flash_array, 0XFF, OUT_FLASH_SIZE);

}

/**
 * @brief 
 * 
 * @param addr 
 * @return uint8_t 
 */
uint8_t out_flash_erase(uint32_t addr)
{
    uint32_t sec_addr = 0;
    
    addr -= OUT_FLASH_ADDR_START;

    if(addr >= OUT_FLASH_SIZE)
    {
        printf("error out flash erase addr is too large\n");
        return 1;
    }

    sec_addr = addr/(OUT_PAGE_SIZE*OUT_PAGES_PER_BLIOCK);

    memset(&out_flash_array[sec_addr], 0XFF, OUT_PAGE_SIZE*OUT_PAGES_PER_BLIOCK);
}

/**
 * @brief 
 * 
 * @param addr 
 * @param buff 
 * @param len 
 * @return uint8_t err return 1  rigth return 0
 */
uint8_t out_flash_read(uint32_t addr, uint8_t* buff, uint16_t len)
{
    addr -= OUT_FLASH_ADDR_START;

    if(addr >= OUT_FLASH_SIZE)
    {
        printf("error out flash read addr is too large\n");
        return 1;
    }
    memcpy(buff, &out_flash_array[addr],  len);
    return 0;
}

/**
 * @brief 
 * 
 * @param addr 
 * @param buff 
 * @param len 
 * @return uint8_t  err return 1  rigth return 0
 */
uint8_t out_flash_write(uint32_t addr, uint8_t* buff, uint16_t len)
{
    addr -= OUT_FLASH_ADDR_START;

    if(addr >= OUT_FLASH_SIZE)
    {
        printf("error: out flash write addr is too large\n");
        return 1;
    }
    memcpy(&out_flash_array[addr], buff, len);
    return 0;
}





void out_flash_print(uint32_t start_addr, uint32_t end_addr)
{
    if(start_addr > end_addr) 
    {
        printf("error: start_addr > end_addr\n");
        return ;
    }

    for(int offset = start_addr,i = 0; offset < end_addr; offset++)
    {
         printf("%#x ",out_flash_array[offset]);
         i++;
         if(i == 8)
         {
            i = 0;
            printf("\n");
         }
    }
   
}


